package com.party.admin.web.controller.copartner;

import com.google.common.collect.Maps;
import com.party.admin.biz.copartner.MemberCopartnerDetailBizService;
import com.party.admin.biz.copartner.TargetCopartnerBizService;
import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.model.activity.Activity;
import com.party.core.model.activity.ActivityInfo;
import com.party.core.model.copartner.BrokerageItem;
import com.party.core.model.copartner.BrokerageStatusEnum;
import com.party.core.model.crowdfund.ProjectBrokerage;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.workflow.BusinessInstance;
import com.party.core.service.activity.IActivityInfoService;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.copartner.IBrokerageItemService;
import com.party.core.service.crowdfund.IProjectBrokerageService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.workflow.IBusinessInstanceService;
import com.party.notify.notifyPush.officialPartner.ICopartnerNotifySendService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: Administrator.
 * @Description: 佣金
 * @Date:Created in 2017/10/24 0024 下午 18:01.
 */
@Controller
@RequestMapping("copartner/brokerage")
public class BrokerageController {
    @Autowired
    private IBusinessInstanceService businessInstanceService;

    @Autowired
    private IProjectBrokerageService projectBrokerageService;

    @Autowired
    private IBrokerageItemService brokerageItemService;

    @Autowired
    private ICopartnerNotifySendService copartnerNotifySendService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private TargetCopartnerBizService targetCopartnerBizService;

    @Autowired
    private MemberCopartnerDetailBizService memberCopartnerDetailBizService;

    @Autowired
    private IActivityInfoService activityInfoService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 佣金审核列表
     *
     * @param page
     * @param input
     * @return
     */
    @RequestMapping("verifyList")
    public ModelAndView verifyList(BusinessInstance instance, Page page, CommonInput input) {
        Map<String, Object> params = CommonInput.appendParams(input);

        if (null != params.get("startDate")) {
            input.setCreateStart(params.get("startDate").toString().substring(0, "2018-05-04".length()));
        }
        if (null != params.get("endDate")) {
            input.setCreateEnd(params.get("endDate").toString().substring(0, "2018-05-04".length()));
        }

        params.put("checkStatus", instance.getCheckStatus());
        page.setLimit(20);
        List<Map<String, Object>> resultList = businessInstanceService.webListPage(params, page);
        ModelAndView mv = new ModelAndView("copartner/verifyList");
        Map<Object, Object> checkStatusMap = Maps.newHashMap();
        checkStatusMap.put(BrokerageStatusEnum.ONE_MONEY_AUDITING.getCode(), "待审核");
        checkStatusMap.put(BrokerageStatusEnum.TWO_FREEZE.getCode(), "审核中");
        checkStatusMap.put(BrokerageStatusEnum.TWO_WITHDRAW.getCode(), "通过");
        checkStatusMap.put(BrokerageStatusEnum.TWO_REJECT.getCode(), "拒绝");
        mv.addObject("checkStatusMap", checkStatusMap);
        mv.addObject("resultList", resultList);
        mv.addObject("page", page);
        mv.addObject("input", input);
        mv.addObject("instance", instance);
        return mv;
    }

    /**
     * 佣金解冻列表
     *
     * @param page
     * @param input
     * @return
     */
    @RequestMapping("freezeList")
    public ModelAndView freezeList(BusinessInstance instance, Page page, CommonInput input) {
        Map<String, Object> params = CommonInput.appendParams(input);

        if (null != params.get("startDate")) {
            input.setCreateStart(params.get("startDate").toString().substring(0, "2018-05-04".length()));
        }
        if (null != params.get("endDate")) {
            input.setCreateEnd(params.get("endDate").toString().substring(0, "2018-05-04".length()));
        }

        params.put("checkStatus", instance.getCheckStatus());
        page.setLimit(20);
        List<Map<String, Object>> resultList = businessInstanceService.webListPage(params, page);
        ModelAndView mv = new ModelAndView("copartner/freezeList");
        Map<Object, Object> checkStatusMap = Maps.newHashMap();
        checkStatusMap.put(BrokerageStatusEnum.ONE_MONEY_AUDITING.getCode(), "待审核");
        checkStatusMap.put(BrokerageStatusEnum.TWO_FREEZE.getCode(), "审核中");
        checkStatusMap.put(BrokerageStatusEnum.TWO_WITHDRAW.getCode(), "通过");
        checkStatusMap.put(BrokerageStatusEnum.TWO_REJECT.getCode(), "拒绝");
        mv.addObject("checkStatusMap", checkStatusMap);
        mv.addObject("resultList", resultList);
        mv.addObject("page", page);
        mv.addObject("input", input);
        mv.addObject("instance", instance);
        return mv;
    }

    /**
     * 审核详情
     *
     * @param instanceId
     * @return
     */
    @RequestMapping("verifyDetail")
    public ModelAndView verifyDetail(String instanceId, String type) {
        ModelAndView mv = new ModelAndView("copartner/verifyDetail");
        if (!StringUtils.isEmpty(instanceId)) {
            Map<String, Object> params = Maps.newHashMap();
            params.put("instanceId", instanceId);
            List<Map<String, Object>> resultList = businessInstanceService.webListPage(params, null);
            mv.addObject("result", resultList.size() > 0 ? resultList.get(0) : null);
        }
        mv.addObject("type", type);
        return mv;
    }

    /**
     * 核算单
     *
     * @param instanceId
     * @return
     */
    @RequestMapping("verifyForm")
    public ModelAndView verifyForm(String instanceId) {
        ModelAndView mv = new ModelAndView("copartner/verifyForm");
        if (!StringUtils.isEmpty(instanceId)) {
            Map<String, Object> params = Maps.newHashMap();
            params.put("instanceId", instanceId);
            List<Map<String, Object>> resultList = businessInstanceService.webListPage(params, null);
            mv.addObject("result", resultList.size() > 0 ? resultList.get(0) : null);
        }
        return mv;
    }

    /**
     * 编辑核算单
     *
     * @param instanceId
     * @return
     */
    @RequestMapping("editForm")
    public ModelAndView editForm(String instanceId) {
        ModelAndView mv = new ModelAndView("copartner/editForm");
        if (!StringUtils.isEmpty(instanceId)) {
            Map<String, Object> params = Maps.newHashMap();
            params.put("instanceId", instanceId);
            List<Map<String, Object>> resultList = businessInstanceService.webListPage(params, null);
            mv.addObject("result", resultList.size() > 0 ? resultList.get(0) : null);
        }
        return mv;
    }

    /**
     * 保存核算单
     *
     * @param projectId  众筹id
     * @param brokerage  佣金
     * @param instanceId 实例id
     * @return
     */
    @ResponseBody
    @RequestMapping("updateBrokerage")
    public AjaxResult updateBrokerage(String projectId, Float brokerage, String instanceId) {
        if (StringUtils.isEmpty(projectId) || StringUtils.isEmpty(instanceId) || brokerage == null) {
            return AjaxResult.error("不能为空");
        }
        ProjectBrokerage pBrokerage = projectBrokerageService.findByProjectId(projectId);
        if (pBrokerage == null) {
            return AjaxResult.error("异常");
        }
        try {
            pBrokerage.setBrokerage(brokerage);
            projectBrokerageService.update(pBrokerage);

            BusinessInstance instance = businessInstanceService.get(instanceId);
            instance.setBrokerage(brokerage);
            businessInstanceService.update(instance);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("编辑核算单异常", e);
            return AjaxResult.error("编辑核算单异常");
        }
    }

    /**
     * 第一步：审核金额
     *
     * @param instanceId
     * @param checkStatus 审核状态
     * @return
     */
    @ResponseBody
    @RequestMapping("checkMoney")
    public AjaxResult checkMoney(String instanceId, Integer checkStatus, String remarks) {
        if (StringUtils.isEmpty(instanceId)) {
            return AjaxResult.error("id不能为空");
        }
        BusinessInstance instance = businessInstanceService.get(instanceId);
        if (instance == null || StringUtils.isEmpty(instance.getTargetId())) {
            return AjaxResult.error("流程错误");
        }
        try {
            String currentId = RealmUtils.getCurrentUser().getId();
            instance.setRemarks(remarks);
            instance.setUpdateBy(currentId);
            checkStatus = checkStatus == null ? BrokerageStatusEnum.ONE_MONEY_AUDIT_PASS.getCode() : checkStatus;
            if (checkStatus.equals(BrokerageStatusEnum.ONE_MONEY_AUDIT_PASS.getCode())) { // 通过
                instance.setStep(2);
                instance.setCheckDate(new Date());
                instance.setCheckStatus(BrokerageStatusEnum.TWO_FREEZE.getCode()); // 冻结状态
                businessInstanceService.update(instance);

                ProjectBrokerage projectBrokerage = projectBrokerageService.findByProjectId(instance.getTargetId());
                if (projectBrokerage != null) {
                    MemberGroup currentUser = RealmUtils.getCurrentUser();
                    BrokerageItem item = new BrokerageItem();
                    item.setCheckStatus(BrokerageStatusEnum.TWO_FREEZE.getCode()); // 冻结状态
                    item.setBrokerage(projectBrokerage.getBrokerage());
                    item.setPartnerId(projectBrokerage.getCopartnerId());
                    item.setTargetId(instance.getTargetId());
                    item.setCreateBy(currentUser.getId());
                    item.setUpdateBy(currentUser.getId());
                    brokerageItemService.insert(item);

                    try {
                        Member author = memberService.get(projectBrokerage.getAuthorId());
                        Member receiver = memberService.get(projectBrokerage.getCopartnerId());
                        Activity activity = activityService.get(projectBrokerage.getTargetId());
                        copartnerNotifySendService.sendBrokerageFirstVerifyPass(author.getRealname(), activity.getTitle(), item, receiver);
                    } catch (Exception e) {
                        logger.error("佣金第一次审核通过推送异常", e);
                    }
                }
            } else if (checkStatus.equals(BrokerageStatusEnum.ONE_MONEY_AUDIT_REJECT.getCode())) { // 拒绝
                instance.setCheckStatus(checkStatus);
                businessInstanceService.update(instance);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("审核金额异常", e);
        }
        return AjaxResult.error("审核金额异常");
    }

    /**
     * 第二部：审核提现
     *
     * @param instanceId
     * @param checkStatus 审核状态
     * @return
     */
    @ResponseBody
    @RequestMapping("checkWithdrawal")
    public AjaxResult checkWithdrawal(String instanceId, Integer checkStatus) {
        if (StringUtils.isEmpty(instanceId)) {
            return AjaxResult.error("id不能为空");
        }
        BusinessInstance instance = businessInstanceService.get(instanceId);
        if (instance == null || StringUtils.isEmpty(instance.getTargetId())) {
            return AjaxResult.error("流程错误");
        }
        try {
            String currentId = RealmUtils.getCurrentUser().getId();
            ProjectBrokerage projectBrokerage = projectBrokerageService.findByProjectId(instance.getTargetId());

            BrokerageItem item = brokerageItemService.getUnique(new BrokerageItem(instance.getTargetId(), BrokerageStatusEnum.TWO_FREEZE.getCode()));
            if (item == null) {
                return AjaxResult.error("审核异常");
            }
            item.setCheckStatus(checkStatus);
            brokerageItemService.update(item);

            if (checkStatus.equals(BrokerageStatusEnum.TWO_WITHDRAW.getCode())) { // 通过
                Member author = memberService.get(projectBrokerage.getAuthorId());
                Member receiver = memberService.get(projectBrokerage.getCopartnerId());
                Activity activity = activityService.get(projectBrokerage.getTargetId());
                try {
                    copartnerNotifySendService.sendBrokerageSecondVerifyPass(author.getRealname(), activity.getTitle(), item, receiver);
                } catch (Exception e) {
                    logger.error("佣金第二次审核通过推送异常", e);
                }

                //同步佣金统计数
                targetCopartnerBizService.updateBrokerage(activity.getId(), item.getBrokerage());
//                memberCopartnerDetailBizService.updateBrokerage(projectBrokerage.getCopartnerId(), item.getBrokerage());
            } else if (checkStatus.equals(BrokerageStatusEnum.TWO_REJECT.getCode())) { // 拒绝
                // 拒绝 保存一条拒绝的流水
//                BrokerageItem item = new BrokerageItem();
//                item.setCheckStatus(BrokerageStatusEnum.TWO_REJECT.getCode()); // 拒绝状态
//                item.setBrokerage(projectBrokerage.getBrokerage());
//                item.setPartnerId(projectBrokerage.getCopartnerId());
//                item.setTargetId(instance.getTargetId());
//                item.setCreateBy(currentId);
//                item.setUpdateBy(currentId);
//                brokerageItemService.insert(item);

                try {
                    Member author = memberService.get(projectBrokerage.getAuthorId());
                    Member receiver = memberService.get(projectBrokerage.getCopartnerId());
                    Activity activity = activityService.get(projectBrokerage.getTargetId());
                    copartnerNotifySendService.sendBrokerageSecondVerifyFail(author.getRealname(), activity.getTitle(), item, receiver);
                } catch (Exception e) {
                    logger.error("佣金第二次审核拒绝推送异常", e);
                }
            }
            instance.setFreezeDate(new Date());
            instance.setUpdateBy(currentId);
            instance.setCheckStatus(checkStatus);
            businessInstanceService.update(instance);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("审核提现异常", e);
        }
        return AjaxResult.error("审核提现异常");
    }

    @ResponseBody
    @RequestMapping("initWithdrawDate")
    public AjaxResult initWithdrawDate() {
        try {
            AtomicInteger count = new AtomicInteger();
            List<String> activityIds = brokerageItemService.distinctActivityId();
            activityIds.forEach(activityId -> {
                ActivityInfo activityInfo = activityInfoService.findByActivityId(activityId);
                if (null != activityInfo && null != activityInfo.getWithdrawDate()) {
                    List<BrokerageItem> brokerageItems = brokerageItemService.getWithdrawDateNull(activityId);
                    brokerageItems.forEach(brokerageItem -> {
                        BrokerageItem t = new BrokerageItem();
                        t.setId(brokerageItem.getId());
                        t.setWithdrawDate(activityInfo.getWithdrawDate());
                        brokerageItemService.update(t);
                        count.getAndIncrement();
                    });
                }
            });
            return AjaxResult.success(count.get());
        } catch (Exception e) {
            logger.error("初始化佣金的可提现日期异常", e);
            return AjaxResult.error("初始化佣金的可提现日期异常");
        }
    }
}
